package com.elf.zero.utils;

import android.util.Base64;

import java.util.Random;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class TripleDESUtils {

    private static final String ALLCHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final int key_length = 32;
    private static final String IV = "66666666";

    /**
     * 生成用户加解密的key
     */
    public static String genKey() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < key_length; i++) {
            sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));
        }
        return sb.toString();
    }

    /**
     * 加密
     */
    public static String encrypt(String key, String data) throws Exception {
        byte[] en_data = encrypt(key, data.getBytes());
        return new String(Base64.encode(en_data, Base64.NO_WRAP));
    }

    /**
     * 加密
     */
    public static byte[] encrypt(String key, byte[] data) throws Exception {
        Cipher cipher = getCipher(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(data);
    }

    /**
     * 解密
     */
    public static String decrypt(String key, String data) throws Exception {
        byte[] t_data = Base64.decode(data.getBytes(), Base64.NO_WRAP);
        byte[] de_data = decrypt(key, t_data);
        return new String(de_data);
    }

    /**
     * 解密
     */
    public static byte[] decrypt(String key, byte[] data) throws Exception {
        Cipher cipher = getCipher(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(data);
    }

    /**
     * 获取密码对象
     */
    private static Cipher getCipher(int mode, String key) throws Exception {
        // convert key
        DESedeKeySpec desKeySpec = new DESedeKeySpec(key.getBytes());
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DESede");
        SecretKey convertedSecretKey = secretKeyFactory.generateSecret(desKeySpec);

        // --加密向量
        final IvParameterSpec iv = new IvParameterSpec(IV.getBytes("UTF-8"));

        // encrypt
        Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        // decrypt
        cipher.init(mode, convertedSecretKey, iv);
        return cipher;
    }
}
